import os
import sys
import cPickle as pickle
import ConfigParser

def gp_run_proc(funcname,cfgpath):
	# parse config file
	sector,infiles,outfiles,params = parseParams(cfgpath)
	
	cfgname = cfgpath[:cfgpath.rfind('.')]
	
	slpos = cfgpath.rfind('/')
	workdir = cfgpath[:(slpos+1)] if slpos>=0 else os.getcwd()+'/'
	
	# dotpos = cfgpath.rfind('.')
	# outdir = cfgpath[:dotpos]+'/' if dotpos>=0 else cfgpath+'/'
	outdir = workdir + cfgname
	if not os.path.exists(outdir):
		os.mkdir(outdir)
	
	# no need
	# exec("sys.path.append('../gptools/')")	
	exec('from %s.%s import %s'%(sector[0],funcname,funcname))	
	# exec funcname()
	
	infiles = [workdir+f for f in infiles]
	outfiles = [outdir+'/'+f for f in outfiles]
	print infiles, outfiles	

	#check if infiles all exist
	for fname in infiles:		
		if not os.path.exists(fname):
			print fname, "doesn't exist! Program stops!!!"
	
	rtn = eval(funcname)(infiles,outfiles,params)	
	
	#check if outfiles exist
	for fname in outfiles:
		if not os.path.exists(fname):
			print 'Output',fname, "doesn't exist! Make sure outputs are generated!!!"
	

# read config file and prepare param dict
def parseParams(cfgpath):
	config  = ConfigParser.ConfigParser()
	
	def get_option(secName):
		dic 	= []	
		for pname in config.options(secName):
			# dic[pname] = config.get(secName,pname)
			dic.append(config.get(secName,pname))
		return dic
		
	cfgfile = open(cfgpath,'r')
	config.readfp(cfgfile)	
	sector		= get_option('SECTOR')
	infiles 	= get_option('INPUTS')
	params 		= get_option('PARAMS')
	outfiles 	= get_option('OUTPUTS')
	cfgfile.close()
	
	return sector,infiles,outfiles,params
	
	
# serialization
# mode
# 'save' : save data anyway
# 'savecheck': save if data file not existing
def _savedata(outfile,mode='save'):  
  def wrapper1(func):
    def wrapper2(*args):  
		if os.path.exists(outfile) and mode=='savecheck':
			return		
		out = func(*args)  
		with open(outfile, 'wb') as f:
			pickle.dump(out, f)
    return wrapper2  
  return wrapper1  

# deserialization   
def _loaddata(infile):  
  def wrapper1(func):
    def wrapper2(*args):   
		indata = []
		with open(infile, 'rb') as f:
			indata = pickle.load(f)
		func(indata,*args)
    return wrapper2  
  return wrapper1   

if __name__ == '__main__':
	if len(sys.argv)==1:
		print 'usage: %s config_file_path'
		exit()
	cfgfile = sys.argv[1]
	
	gp_run_proc('calc_potential','calc_potential.cfg')
	# parseParams('calc_potential.cfg')